//created by: Justina Lee
Ext.define('MajorProjectSenchaTouch.controller.BookMarked', {
    extend: 'Ext.app.Controller',
    config:{
        views:['BookMarkedModule.BookMarked', 'BookMarkedModule.BookMarkedDataview', 
        'BookMarkedModule.ResultListItem', 'SearchModule.ResultList', 'BookMarkedModule.BookMarkedInfo', 'MainNavView'],
        refs:{
            removeAllButton: 'button[action=clearBookMarkedList]',
            infoButton: 'button[action=showBookMakedInfo]',
                        
            bookMarkedBtn: '#bookMarkedBtn',
            bookMarkedList: 'BookMarkedDV',
            
            bookMarkedListPaging: '#bmListPaging',
            loadMoreCmp: '#bmLoadMoreCmp',
            
            resultList: 'resultpage',
            resultListItem: 'rlistItem', 
            mainTabDV: 'maintabdataview',
            
            closeBtn: '#closeBtn',
            bookMarkedInfo: 'bookmarkedInfoPage',
            
            lastTapTimestamp: 0
        },        
        control:{
            removeAllButton :{
                tap: 'removeAllBookmarks'
            },
            resultListItem: {
                bookMarkedBtnTap : 'bookMarkedTap'
            },
            mainTabDV:{
                tapDetailsBMBtn: 'detailsBookMarkedTap'  
            },
            bookMarkedList:{
                loadMoreRecords: 'loadMore'
            },
            infoButton:{
                tap: 'showInfo'
            },
            bookMarkedInfo:{
                initialize: 'initPopup'
            },
            bookMarkedBtn:{
                initBtn: 'initBadgeText'
            },
            closeBtn:{
                tap: 'hidePopup'
            }
        }
    },
    /*
|--------------------------------------------------------------------------
| initBadgeText (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| Initialize the badge text of the bookmark module button at the top 
| right corner.
|
*/
    initBadgeText:function(btn){
        var bmStore = Ext.getStore('BookMarked');
        var bmCount = bmStore.getCount();
        
        if(bmCount > 0){
            btn.setBadgeText(bmCount);
        }
    },
    /*
|--------------------------------------------------------------------------
| removeAllBookmarks (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| This function shows a confirmation message. If the user tapped on 'Yes',
| all bookmarks are removed from the bookmarked (HTML5 localstorage) and 
| bookmarkedMemory stores. The badgetext of the bookmark module button 
| is removed.
|
*/
    removeAllBookmarks:function(){
        var bmStore = Ext.getStore('BookMarked');
        var bmMemoryStore = Ext.getStore('BookMarkedMemory');
        var resultList = this.getResultList();        
        var bmBtn  = this.getBookMarkedBtn();
        var count = bmStore.getCount();
        var bmCtrl = this;
        
        if(count > 0){
            Ext.Msg.confirm("Confirmation", "Are you sure you want to remove all bookmarks?", function(e)
            {
                if(e == 'yes'){  
                    if(typeof resultList != 'undefined'){
                        var rStore = Ext.getStore('Results');  
                        rStore.each(function(record){
                            //get index of item in Results store
                            var resultIndex = rStore.find("docnum", record.get("docnum"));                
                            if(resultIndex != -1){
                                //get item from result list based on index
                                var resultItem = resultList.getViewItems()[resultIndex];
                                //get bookmarked button in the item
                                var bmButton = resultItem._bookMarkedButton;
                                //change button to "add" icon"
                                bmButton.setCls('btnAddBookMarked');
                            }
                        });                       
                    }
                    bmStore.removeAll();   
                    bmMemoryStore.removeAll();
                    
                    //remove badge text
                    bmBtn.setBadgeText(null);
                    
                    //change loadMore text to "No Bookmarks"
                    bmCtrl.removeLoadMoreText('- No Bookmarks -');
                }
            });
        }
    },
    /*
|--------------------------------------------------------------------------
| bookMarkedTap (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| This function is triggered when the user tap on the add/remove bookmark
| button at the bottom right of the result list item.
|
*/
    bookMarkedTap: function(item, button, e){
        var record = item.getRecord();
        
        this.delayBtnTap();
        
        this.checkForBookMarked('bookMarkedTap', button, item, record, null);                   
                
        e.stopEvent();
    },
    
    /*
|--------------------------------------------------------------------------
| detailsBookMarkedTap (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| This function is triggered when the user tapped on the bookmarked button
| at the details view. 
|
*/
    detailsBookMarkedTap: function(record, tappedTarget){
        this.delayBtnTap();
        
        this.checkForBookMarked('detailsBookMarkedTap', null, null, record, tappedTarget);
    },
    
    /*
|--------------------------------------------------------------------------
| checkForBookMarked (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| Checks if item exist in the bookmarked store. If yes, remove bookmark else
| add item into store. Changes the button class to the correct button icon.
| This function is used by bookMarkedTap or detailsBookMarkedTap function.     
|
*/
    checkForBookMarked : function(functionName, button, item, record, tappedTarget){
        var ctrl = this;
        var rStore, resultIndex, resultItem, bmButton, resultList, bmList, detailsDV;
        var detailsViewCtrl = MajorProjectSenchaTouch.app.getController('DetailsView'); 
        
        var bmStore = Ext.getStore('BookMarked');
        var bmMemoryStore = Ext.getStore('BookMarkedMemory');         
        var bmBtn  = this.getBookMarkedBtn();
        
        //find record in localstorage
        var index = bmStore.find("docnum", record.get("docnum"));
        var memoryIndex = bmMemoryStore.find("docnum", record.get("docnum"));
        
        if(index === -1){
            if(functionName == "bookMarkedTap"){
                /* The getDetails function in DetailsView controller is called
                * which gets the detailed information of the item and triggers
                * the addBookmark function in this controller.*/                           
                detailsViewCtrl.getDetails(null, null, item);
            
                button.setCls('btnRemoveBookMarked');
                
            }else if(functionName == "detailsBookMarkedTap"){
                ctrl.addBookMark(detailsViewCtrl.disclosure, record);
                
                tappedTarget.setAttribute("class", "btnRemoveBookMarked");
                
                //if result list is defined, need to change the bookmarked icon
                resultList = ctrl.getResultList(); 
                bmList = ctrl.getBookMarkedList();
                
                if(typeof resultList != 'undefined'){
                    rStore = Ext.getStore('Results');
                    //get index of item in Results store
                    resultIndex = rStore.find("docnum", record.get("docnum"));                
                    if(resultIndex != -1){
                        //get item from result list based on index
                        resultItem = resultList.getViewItems()[resultIndex];
                        //get bookmarked button in the item
                        bmButton = resultItem._bookMarkedButton;
                        //change button to "add" icon"
                        bmButton.setCls('btnRemoveBookMarked');
                    }
                }
                
                if(typeof bmList != 'undefined'){
                    var bmIndex = bmStore.find("docnum", record.get("docnum"));
                    console.log(bmIndex);
                    
                    var getItem = bmStore.getRange(bmIndex);
                    
                    bmMemoryStore.add(getItem);
                    bmMemoryStore.sync();
                }
                
                
            }
                    
            //set badge text
            var badgeTextCount = bmBtn._badgeText;
            if(badgeTextCount == null){
                bmBtn.setBadgeText(0);
            }
            
            bmBtn.setBadgeText(parseInt(bmBtn._badgeText) + 1); 
            
        }else{            
            bmStore.removeAt(index); 
            bmStore.sync();
            
            //set badge text
            this.setBadgeText(bmBtn);
            
            if(memoryIndex != -1)
                bmMemoryStore.removeAt(memoryIndex);
            
            //change button icon to remove bookmark icon
            if(functionName == "bookMarkedTap"){
                button.setCls('btnAddBookMarked'); 
                
            }else if(functionName == "detailsBookMarkedTap"){                
                tappedTarget.setAttribute("class", "btnAddBookMarked");
            }            
            
            resultList = this.getResultList(); 
            detailsDV = this.getMainTabDV();
            
            //if result list exist, change the icon to add bookmark
            if(typeof resultList != 'undefined'){
                rStore = Ext.getStore('Results');
                //get index of item in Results store
                resultIndex = rStore.find("docnum", record.get("docnum"));                
                if(resultIndex != -1){
                    //get item from result list based on index
                    resultItem = resultList.getViewItems()[resultIndex];
                    //get bookmarked button in the item
                    bmButton = resultItem._bookMarkedButton;
                    //change button to "add" icon"
                    bmButton.setCls('btnAddBookMarked');
                }
            }
            
            //if details dataview exist, refresh dataview.
            if(typeof detailsDV != 'undefined'){
                detailsDV.refresh();
            }
        }
    },

    
    /*
|--------------------------------------------------------------------------
| addBookMark (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| This function is triggered from the getDetails function in DetailsView
| controller. The selected record is added into the bookmarked store 
| (HTML5 localstorage).    
|
*/
    addBookMark:function(record, details){
        //persist data
        var persistData = {
            docnum:record.get('docnum'),
            setentry:record.get('setentry'),
            bktitle:record.get('bktitle'),
            author:record.get('author'),
            img:record.get('img'),
            callnumber:record.get('callnumber'),
            year:record.get('year'),
            bkformat:record.get('bkformat'),
            ebooklink:record.get('ebooklink'),
            
            //additional fields for details
            edition:details.get('edition'),
            publisher:details.get('publisher'),
            desc:details.get('desc'),
            isbn13:details.get('isbn13'),
            issn:details.get('issn'),
            isbn10:details.get('isbn10'),
            summary:details.get('summary'),
            frequency:details.get('frequency'),
            eBkLink:details.get('eBkLink'),
            img_link:details.get('img_link')
        };
        
        var bmStore = Ext.getStore('BookMarked');
        bmStore.add(persistData);  
        bmStore.sync();
    },
    /*
|--------------------------------------------------------------------------
| setBadgeText (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| Set the badge text of the bookmarked module button using the total count
| of records in the bookmarked store.
|
*/
    setBadgeText: function(button){
        var bmStore = Ext.getStore('BookMarked');
        var count = bmStore.getCount();
        
        button.setBadgeText(count);
    },
    /*
|--------------------------------------------------------------------------
| loadMore (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| When the list reaches the end, more records is added into the boomarkedMemory
| store which append the records to the end of the list.
|   
| If there is no more records to retrieve, the load more text at the bottom of
| the screen is set to "No More Records"
|
*/
    loadMore: function(){
        var bmStore = Ext.getStore('BookMarked');
        var bmMemoryStore = Ext.getStore('BookMarkedMemory'); 
            
        //find number of items in bmStore
        var bmCount = bmStore.getCount();
        //find number of items in bmMemoryStore
        var memoryCount = bmMemoryStore.getCount();
            
        if(bmCount > memoryCount){
            //get next ten items from bmStore
            var endIndex = memoryCount + 9;
            if(endIndex >= bmCount){
                endIndex = bmCount - 1;
            }
            
            var items = bmStore.getRange(memoryCount, endIndex);
            bmMemoryStore.add(items);
            memoryCount = bmMemoryStore.getCount();
        }
        
        if (bmCount == memoryCount && bmCount != 0){
            this.removeLoadMoreText('No More Records');
        }
    },
    /*
|--------------------------------------------------------------------------
| removeLoadMoreText (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| Sets the load more text message
|
*/
    removeLoadMoreText: function(msg){       
        var listPaging = this.getBookMarkedListPaging();
        var loadCmp  = listPaging.addLoadMoreCmp();
        var template = listPaging.getLoadTpl();
            
        //remove 'Loading...' text
        loadCmp.setHtml(template.apply({
            cssPrefix: Ext.baseCSSPrefix,
            message: msg
        }));
    },
    /*
|--------------------------------------------------------------------------
| initPopup (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| Sets the width and height of the bookmarked module info modal panel based
| on the viewport size to do dynamic sizing.
|
*/
    initPopup: function(){
        var infoPanel = this.getBookMarkedInfo();
        
        //check viewport width & height, calculate desired width & height  
        var viewWidth = Ext.Viewport.getWindowWidth(),
        desiredWidth = Math.min(viewWidth, 400) - 20;

        var viewHeight = Ext.Viewport.getWindowHeight(),
        desiredHeight = Math.min(viewHeight, 350) - 40;             

        infoPanel.setWidth(desiredWidth);
        infoPanel.setHeight(desiredHeight);
    },
    /*
|--------------------------------------------------------------------------
| showInfo (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| Show the bookmarked info modal panel when the user tap on the info button
|
*/
    showInfo: function(){
        var infoPanel = this.getBookMarkedInfo();
        
        if(typeof infoPanel == 'undefined'){
            infoPanel = Ext.create('MajorProjectSenchaTouch.view.BookMarkedModule.BookMarkedInfo');
            Ext.Viewport.add(infoPanel);            
        }else{
            infoPanel.show();
        }
    },
    /*
|--------------------------------------------------------------------------
| showInfo (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| Hide the bookmarked info modal panel when the user tap on the close button
|
*/
    hidePopup: function(){
        var infoPanel = this.getBookMarkedInfo();
        infoPanel.hide();
    },
    
    /*
|--------------------------------------------------------------------------
| delayBtnTap (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| Prevents the user from multiple clicks.
|
*/
    delayBtnTap: function(){
        var ctrl = this,
        now = Date.now();

        if (now < ctrl.lastTapTimestamp + 300) {
            ctrl.lastTapTimestamp = now;
            return;
        }
        ctrl.lastTapTimestamp = now;
    }
});

